<template>
  <view class="search-page page-background">
    <CustomNavbar title="搜索" :isBack="true" mode="search" />
    
    <view class="search-content">
      <view class="search">
        <u-search
          placeholder="请输入关键词"
          v-model="keyword"
          shape="round"
          @search="handleSearch"
          @custom="handleSearch"
        ></u-search>
      </view>

      <view class="search-recommend" v-if="textList.length">
        <text>热门搜索</text>
        <view class="tags">
          <u-tag
            v-for="(item, index) in textList"
            :key="index"
            :text="item.keyword"
            mode="plain"
            :closeable="true"
            @click="handleSearch(item.keyword)"
            @close="handleClose(index)"
          />
        </view>
      </view>

      <view class="content">
        <navigator
          v-for="(item, index) in classStore.categoryDetailList"
          :key="item._id + String(index)"
          :url="`/pages/preview/index?id=${item._id}`"
          open-type="navigate"
          hover-class="navigator-hover"
        >
          <u-image
            width="100%"
            height="540rpx"
            :src="item.smallPicurl?.replace(/`/g, '')"
            border-radius="20rpx"
            mode="aspectFill"
          >
            <template #loading><u-loading /></template>
            <template #error><view style="font-size: 24rpx">加载失败</view></template>
          </u-image>
        </navigator>
      </view>

      <view v-if="keyword && !classStore.categoryDetailList.length" class="empty-result">
        <u-empty text="暂无搜索结果" mode="search" />
      </view>

      <u-loadmore
        bg-color="#f8f8f8"
        :status="loadStatus"
        @loadmore="loadMoreData"
      />
    </view>

    <u-back-top :scroll-top="scrollTop" />
  </view>
</template>

<script setup>
  import { ref} from 'vue';
  import { onPageScroll, onReachBottom, onUnload } from '@dcloudio/uni-app';
  import { searchAPI } from '@/api/class';
  import { useClassStore } from '@/stores/class';
import { $u } from 'uview-pro';
import CustomNavbar from '../../components/UI/custom.vue'
import { onReady } from '@dcloudio/uni-app';
  const classStore = useClassStore();
  const scrollTop = ref(0);
  const keyword = ref('');
  const isLoading = ref(false);
  const loadStatus = ref('loadmore');
  const textList = ref([
    { keyword: '帅哥' },
    { keyword: '宠物' },
    { keyword: '美女' },
    { keyword: 'AI' }
  ]);
  // 计算属性
//   const hasMore = computed(() => classStore.categoryDetailList.length < classStore.total);
  // 搜索处理
  const handleSearch = async (searchKeyword = '') => {
    const searchText = searchKeyword || keyword.value;
    if (!searchText.trim()) {
        //   uni.showToast({ title: '请输入关键词', icon: 'none' });
    $u.toast('请输入关键词','error');
      return;
    }
// keyword留起来底部上拉加载使用
      keyword.value = searchText;
    
    isLoading.value = true;

    try {
      const res = await searchAPI({ keyword: searchText, pageNum: classStore.pageNum, pageSize: classStore.pageSize });
      if (res.errCode === 0) {
        classStore.setCategoryDetailList(res.data);
          classStore.setTotal(res.total||res.data.length);
      } else {
        $u.toast(res.errMsg || '搜索失败','error');
      }
    } catch {
      $u.toast('网络错误','error');
    } finally {
      isLoading.value = false;
    }
  };

  // 加载更多
  const loadMoreData = async () => {
    // 在加载且没
    if (isLoading.value || loadStatus.value==='nomore') return;

    isLoading.value = true;
    classStore.setPageNum(classStore.pageNum + 1);

    try {
      const res = await searchAPI({ keyword: keyword.value, pageNum: classStore.pageNum, pageSize: classStore.pageSize });
      if (res.errCode === 0) {
          classStore.addCategoryDetailList(res.data);
        // 判断是否还有更多数据
  loadStatus.value =
    classStore.categoryDetailList.length >= classStore.total ? 'nomore' : 'loadmore'
      } else {
        $u.toast(res.errMsg || '加载失败','error');
      }
    } catch {
      $u.toast('网络错误','error');
    } finally {
      isLoading.value = false;
    }
  };

  // 标签关闭
  const handleClose = index => textList.value.splice(index, 1);

  // 生命周期
  onPageScroll(e => scrollTop.value = e.scrollTop);
onReachBottom(() => { 
    loadMoreData();
})
onReady(() => {
    classStore.resetPagination();
})
  // 页面卸载时清空数据
  onUnload(() => {
    classStore.resetSearchPagination();
  });
</script>

<style scoped lang="scss">
  @import '@/common/style/page-background.scss';
  
  .search-page .search-content{
    padding: 0;
  }
  .search {
    padding: 30rpx;
    background: #fff;
    margin-bottom: 20rpx;
  }

  .search-recommend {
    padding: 30rpx;
    background: #fff;
    margin-bottom: 20rpx;

    text {
      display: block;
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 30rpx;
    }
  }

  .tags {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
  }

  .content {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 5rpx;
    padding: 0 16rpx;
  }

  .empty-result {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300rpx;
  }
</style>
